from flask import Flask, render_template
from flask_cors import CORS
import os
import logging
from api.services.neo4j_service import neo4j_service

def create_app():
    app = Flask(__name__, 
                static_folder='static',
                template_folder='templates')
    CORS(app)
    
    # Load configuration
    app.config.from_object('api.config.database')
    
    # Initialize database on startup
    initialize_database_on_startup()
    
    # Register blueprints
    from api.handlers.qa_handler import qa_bp
    app.register_blueprint(qa_bp, url_prefix='/api')
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    @app.route('/health')
    def health_check():
        return {'status': 'ok', 'message': 'Medical QA System is running'}
    
    @app.route('/api/database/status')
    def database_status():
        """获取数据库状态的API端点"""
        try:
            status = neo4j_service.check_database_status()
            return {'status': 'success', 'data': status}
        except Exception as e:
            return {'status': 'error', 'message': str(e)}, 500
    
    return app

def initialize_database_on_startup():
    """
    应用启动时初始化数据库
    Initialize database on application startup
    """
    try:
        logging.info("检查Neo4j数据库状态...")
        
        # 检查数据库是否已初始化
        if not neo4j_service.is_initialized():
            logging.info("数据库未初始化，开始自动初始化...")
            
            # 获取数据文件路径
            data_dir = os.path.join(os.path.dirname(__file__), 'api', 'data')
            medical_data_path = os.path.join(data_dir, 'medical_data.json')
            knowledge_graph_path = os.path.join(data_dir, 'knowledge_graph.json')
            
            # 检查文件是否存在
            if os.path.exists(medical_data_path) and os.path.exists(knowledge_graph_path):
                neo4j_service.initialize_database(
                    medical_data_path=medical_data_path,
                    knowledge_graph_path=knowledge_graph_path
                )
                logging.info("数据库初始化完成")
            else:
                logging.warning("数据文件不存在，跳过自动初始化")
        else:
            logging.info("数据库已初始化")
            
        # 显示数据库状态
        status = neo4j_service.check_database_status()
        logging.info(f"数据库状态: {status.get('total_nodes', 0)} 个节点, {status.get('total_relationships', 0)} 个关系")
        
    except Exception as e:
        logging.warning(f"数据库初始化失败，应用将继续运行: {str(e)}")
        # 不抛出异常，让应用继续运行

if __name__ == '__main__':
    # 设置日志
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    
    app = create_app()
    print("🏥 医疗问答系统启动中...")
    print("访问 http://localhost:5000 查看应用")
    print("访问 http://localhost:5000/api/database/status 查看数据库状态")
    app.run(debug=True, host='0.0.0.0', port=5000)